from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.hashers import make_password, check_password
from myadmin.models import Users
from alidayu import AlibabaAliqinFcSmsNumSendRequest
import json

# Create your views here.
#登录
def myhome_login(request):
    if request.method=="POST":
        try:
            ob = Users.objects.get(phone=request.POST['phone'])
            # 验证密码
            res = check_password(request.POST['password'], ob.password)
            if res:
                # 验证成功
                request.session['VipUser'] = {'uid': ob.id, 'nikename': ob.nikename, 'phone': ob.phone,
                                              'pic_url': ob.pic_url}
                return HttpResponse('<script>alert("登录成功");location.href="/";</script>')

        except:
            pass

        return HttpResponse('<script>alert("手机号或密码不正确");location.href="/login/";</script>')
    else:
        return render(request,'myhome/login/login.html')

def myhome_logout(request):
    del request.session['VipUser']
    return HttpResponse('<script>alert("退出登录");location.href="/";</script>')

#注册
def myhome_register(request):
    if request.method == "POST":
        return HttpResponse(sendmsg(request.POST['phone']))
    else:
        return render(request,'myhome/login/register.html')
def sendmsg(phone):
    # 其中appkey和secret是必须的参数
    # url可选，默认为沙箱的URL，正式应用请传入 https://eco.taobao.com/router/rest
    # partner_id为可选，其值为下载的TOP SDK中的top/api/base.py里的SYSTEM_GENERATE_VERSION
    req = AlibabaAliqinFcSmsNumSendRequest("LTAI250akYePlzjL", " Tz6Hk80G0EUz0RaM5aRElUuMVUKyZJ",  "v20170525")

    req.extend = "123456"
    req.sms_type = "normal"
    req.sms_free_sign_name = "王朴"
    params = "{\"code\":\"12345\"}"
    req.sms_param = json.dumps(params)
    req.rec_num = phone
    req.sms_template_code = "SMS_96800061"
    try:
        resp = req.getResponse()
        print(resp)
    except Exception as e:
        print(e)
